import {PlusOutlined, UploadOutlined} from '@ant-design/icons';
import {Button, Drawer, FormInstance, message, Popconfirm, Space, Spin, Upload} from 'antd';
import React, {useRef, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {
  addTrouble,
  distribute,
  doFirst,
  getTrouble,
  initTrouble,
  loadTrouble,
  removeTrouble,
  updateTrouble
} from './service';
import type {TroubleListItem, TroubleListPagination} from './data';
import {loadOrgSelect} from '@/pages/Enterprise/Org/service';
import {loadPostSelect} from '@/pages/Enterprise/Post/service';
import {loadEmployeeSelect} from '@/pages/Employee/List/service';
import CheckModule from '@/components/CheckModule';

/**
 * 新增或更新隐患信息
 *
 * @param fields
 */

const handleAdd = async (fields: TroubleListItem, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');
  try {
    mode ? await updateTrouble({...fields}) : await addTrouble({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除隐患
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: TroubleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeTrouble(selectedRows.map((row) => row.troubleId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const sourceTypeData = {
  1: {
    text: '人的不安全行为',
  },
  2: {
    text: '物的不安全状态',
  },
  3: {
    text: '不良环境',
  },
  4: {
    text: '管理缺陷',
  },
};
const proposalData = {
  立即整改: '立即整改',
  限时整改: '限时整改',
  停业整改: '停业整改',
};
const troubleLevelData = {
  2: {
    text: '一般',
    color: '#E1E13A',
  },
  4: {
    text: '重大',
    color: '#FF0000',
  },
};
const frequencyData = {
  1: {
    text: '每日一次',
  },
  2: {
    text: '每周一次',
  },
  3: {
    text: '每月一次',
  },
  4: {
    text: '每季度一次',
  },
  5: {
    text: '每年一次',
  },
  6: {
    text: '每半年一次',
  },
  0: {
    text: '仅一次',
  },
};
const requestOrg = async () => {
  return loadOrgSelect({status: '0'}).then(({data}) => {
    return data;
  });
};
const requestPost = async () => {
  return loadPostSelect().then(({data}) => {
    return data;
  });
};

const requestEmployee = async (param: any) => {
  return loadEmployeeSelect(param).then(({data}) => {
    return data;
  });
};

const TroublePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<TroubleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TroubleListItem[]>([]);
  const columns: ProColumns<TroubleListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '作业位置场所',
      dataIndex: 'place',
      render: (_, record) => <a onClick={() => {
        setCurrentRow(record);
        setShowDetail(true);
      }}>{record?.place}</a>,
    },
    {
      title: '隐患源分类',
      dataIndex: 'sourceType',
      valueEnum: sourceTypeData,
    },
    {
      title: '隐患内容',
      dataIndex: 'source',
      hideInTable: true,
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.measure}</span>,
    },
    {
      title: '排查方式',
      dataIndex: 'checkMode',
      hideInTable: true,
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.checkMode}</span>,
    },

    {
      title: '隐患级别',
      dataIndex: 'level',
      valueEnum: troubleLevelData,
    },

    {
      title: '整改建议',
      dataIndex: 'proposal',
      valueEnum: proposalData,
    },
    {
      title: '整改措施',
      dataIndex: 'measure',
      hideInTable: true,
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.measure}</span>,
    },
    {
      title: '排查频次',
      dataIndex: 'frequency',
      valueEnum: frequencyData,
    },
    {
      title: '责任岗位',
      key: 'postId',
      dataIndex: 'postId',
      valueType: 'select',
      // @ts-ignore
      request: async () => {
        return loadPostSelect().then(({data}) => {
          return data;
        });
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      valueEnum: {
        0: {
          text: '待审核',
          status: 'Default',
        },
        1: {
          text: '启用',
          status: 'Success',
        },
        2: {
          text: '禁用',
          status: 'Error',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
      defaultSortOrder: 'descend',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        if (record.status == '2' || record.status == '1') {
          return (
            <>
              <Space size="small">
                <a
                  key="view"
                  onClick={() => {
                    setCurrentRow(record);
                    setShowDetail(true);
                  }}
                >
                  查看
                </a>
                <a
                  key="edit"
                  onClick={() => {
                    formRef.current?.resetFields();
                    record.checkStatus = 0;
                    setCurrentRow(record);
                    setCheckMode(false);
                    setEditMode(true);
                    handleModalVisible(true);
                  }}
                >
                  编辑
                </a>

                <Popconfirm
                  key="delete"
                  okButtonProps={{danger: true}}
                  title={`确认删除风险数据?`}
                  onConfirm={async () => {
                    setCurrentRow(record);
                    await handleRemove([record]);
                    actionRef.current?.reloadAndRest?.();
                  }}
                  okText="删除"
                  cancelText="取消"
                >
                  <a href="#"> 删除 </a>
                </Popconfirm>
              </Space>
            </>
          );
        } else if (record.status == '0') {
          return (
            <a
              key="edit"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setEditMode(true);
                setCheckMode(true);
                handleModalVisible(true);
              }}
            >
              审核
            </a>
          );
        }
        return <></>;
      },

      // render: (_, record) => [
      //   <a
      //     key="view"
      //     onClick={() => {
      //       setCurrentRow(record);
      //       setShowDetail(true);
      //     }}
      //   >
      //     查看
      //   </a>,
      //   <a
      //     key="edit"
      //     onClick={() => {
      //       formRef.current?.resetFields();
      //       setCurrentRow(record);
      //       setEditMode(true);
      //       handleModalVisible(true);
      //     }}
      //   >
      //     编辑
      //   </a>,

      //   <Popconfirm
      //     key="delete"
      //     okButtonProps={{danger: true}}
      //     title={`确认删除隐患数据?`}
      //     onConfirm={async () => {
      //       setCurrentRow(record);
      //       await handleRemove([record])
      //       actionRef.current?.reloadAndRest?.();
      //     }}
      //     okText="删除"
      //     cancelText="取消"
      //   >
      //     <a href="#"> 删除 </a>
      //   </Popconfirm>

      // ],
    },
  ];
  const [editMode, setEditMode] = useState<boolean>(false);
  const [checkMode, setCheckMode] = useState<boolean>(false);
  let troubleColor = {'4': '#FF0000', '3': '#FFA500', '2': '#E1E13A', '1': '#0000FF'};

  const [spinning, setSpinning] = useState(false);
  const [uploading, setUploading] = useState(false);
  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
      TenantCode: 'e513f45c099239505054fead0a445fa2'
    },
    multiple: false,
    // onPreview: async (file: UploadFile) => {
    //   window.open(file?.response?.data?.path || file.url, '_blank')
    // },
    name: 'file',
    max: 1,
  };
  return (
    <CheckModule code={'SC'}>
      <Spin spinning={spinning} tip="正在处理中，请勿关闭当前页面！">
        <PageContainer waterMarkProps={{content: ''}}>
          <ProTable<TroubleListItem, TroubleListPagination>
            headerTitle="隐患列表"
            actionRef={actionRef}
            rowKey="troubleId"
            search={{
              labelWidth: 120,
            }}
            toolBarRender={() => [
              // <Popconfirm
              //   key="init"
              //   okButtonProps={{danger: true}}
              //   title={
              //     <div style={{color: 'red'}}>
              //       <div>
              //         重置将<span style={{color: 'red'}}>清空</span>现在隐患数据库!
              //       </div>
              //       <div>确认是否重置?</div>
              //     </div>
              //   }
              //   onConfirm={async () => {
              //     setSpinning(true);
              //     await initTrouble();
              //     setSpinning(false);
              //     actionRef.current?.reloadAndRest?.();
              //     message.success('操作成功');
              //   }}
              //   okText="重置"
              //   cancelText="取消"
              // >
              //   <Button type="primary" danger>
              //     重置风险库
              //   </Button>,
              // </Popconfirm>,
              <Button
                type="primary"
                key="template"
                onClick={async () => {
                  location.href = "https://cdn.51zasafe.com/zun/template/%E9%9A%90%E6%82%A3%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
                  // await download();
                }}
              >
                下载模板
              </Button>,
              <Button
                type="primary"
                key="distribute"
                onClick={async () => {
                  setSpinning(true);
                  await distribute();
                  setSpinning(false);
                  message.success('操作成功');
                }}
              >
                异常修复
              </Button>,
              <Popconfirm
                key="first"
                okButtonProps={{danger: true}}
                title={
                  <div>
                    <div style={{color: 'red'}}>
                      警告:请谨慎操作！！！
                    </div>
                    <div>
                      首次下发前请确认对应岗位上有员工
                    </div>
                    <div>确认是否下发?</div>
                  </div>
                }
                onConfirm={async () => {
                  setSpinning(true);
                  await doFirst();
                  setSpinning(false);
                  message.success('操作成功');
                }}
                okText="下发"
                cancelText="取消"
              >
                <Button
                  type="primary"
                  key="first"
                >
                  任务补发
                </Button>
              </Popconfirm>,
              <Upload
                key="upload"
                {...uploadProps}
                accept={'.xls,.xlsx'}
                action={'/v2/enterprise/trouble/import'}
                showUploadList={false}
                onChange={async (data) => {
                  let file = data.file;
                  if (file.status === 'uploading') {
                    setUploading(true);
                  } else {
                    setUploading(false);
                  }
                  if (file.status === 'done' && file.response.code !== 200) {
                    message.error(file.response.msg);
                    file.status = 'error';
                  } else if (file.status === 'done' && file.response.code === 200) {
                    message.success('上传成功');
                    // @ts-ignore
                    actionRef?.current?.reloadAndRest();
                  }
                }}
              >
                <Button type="primary" loading={uploading} icon={<UploadOutlined/>}>
                  导入
                </Button>
              </Upload>,
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setEditMode(false);
                  handleModalVisible(true);
                }}
              >
                <PlusOutlined/> 新建
              </Button>,
            ]}
            request={loadTrouble}
            columns={columns}
            rowSelection={{
              onChange: (_, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }}
          />
          {selectedRowsState?.length > 0 && (
            <FooterToolbar
              extra={
                <div>
                  已选择{' '}
                  <a
                    style={{
                      fontWeight: 600,
                    }}
                  >
                    {selectedRowsState.length}
                  </a>{' '}
                  个隐患
                </div>
              }
            >
              <Popconfirm
                key="delete"
                title={`确认删除选中的${selectedRowsState.length}个隐患?`}
                okButtonProps={{danger: true}}
                onConfirm={async () => {
                  await handleRemove(selectedRowsState);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                }}
                okText="删除"
                cancelText="取消"
              >
                <Button danger>批量删除</Button>
              </Popconfirm>
              {/*<Button type="primary">批量审批</Button>*/}
            </FooterToolbar>
          )}
          <ModalForm<TroubleListItem>
            // title={currentRow?.troubleId || 0 > 0 ? '编辑隐患' : '新建隐患'}
            title={
              currentRow?.troubleId || 0 > 0 ? (checkMode ? '审核隐患' : '编辑隐患') : '新建隐患'
            }
            // width="600px"
            modalProps={{destroyOnClose: true, maskClosable: false}}
            layout={'horizontal'}
            labelCol={{span: 5}}
            wrapperCol={{pull: 1, offset: 1, span: 17}}
            formRef={formRef}
            // size={"large"}
            visible={createModalVisible}
            onValuesChange={(f, v) => {
              if (f.hasOwnProperty('orgId') || f.hasOwnProperty('postId')) {
                formRef.current?.setFieldsValue({employeeId: undefined});
              }
            }}
            onVisibleChange={(visible) => {
              if (!visible) {
                setCurrentRow(undefined);
              }
              handleModalVisible(visible);
            }}
            onFinish={async (value) => {
              const success = await handleAdd(value, editMode);
              if (success) {
                handleModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            request={(params) => {
              if (params.troubleId > 0) {
                return getTrouble(params).then(({data}) => {
                  return data;
                });
              } else {
                return new Promise<TroubleListItem>((resolve) => {
                  resolve({troubleId: 0});
                });
              }
            }}
            params={{...currentRow}}
          >
            <ProFormText hidden name="troubleId"/>
            <ProFormSelect
              name="postId"
              label={'责任岗位'}
              rules={[{required: true}]}
              request={requestPost}
              disabled={editMode && !checkMode}
              fieldProps={{
                placeholder: '请选择责任岗位',
                dropdownMatchSelectWidth: false,
              }}
            />
            <ProFormTreeSelect
              name="orgId"
              label={'责任部门'}
              request={requestOrg}
              tooltip={'责任部门可以限定到部门对应的的岗位'}
              disabled={editMode && !checkMode}
              fieldProps={{
                allowClear: true,
                placeholder: '请选择部门',
                treeDefaultExpandAll: true,
                treeLine: true,
                fieldNames: {label: 'label', value: 'id', children: 'children'},
              }}
            />
            <ProFormDependency name={['postId', 'orgId']}>
              {({postId, orgId}) => {
                if (postId || orgId) {
                  return (
                    <ProFormSelect
                      name="employeeId"
                      label={'责任人'}
                      tooltip={'可以将隐患限定到对应的人员'}
                      request={requestEmployee}
                      disabled={editMode && !checkMode}
                      params={{postId, orgId}}
                      fieldProps={{
                        placeholder: '请选择责任岗位',
                        dropdownMatchSelectWidth: false,
                      }}
                    />
                  );
                }
                return null;
              }}
            </ProFormDependency>
            <ProFormText rules={[{required: true}]} label={'作业位置场所'} name="place"/>
            <ProFormSelect
              rules={[{required: true}]}
              label={'隐患源类型'}
              name="sourceType"
              valueEnum={sourceTypeData}
            />
            <ProFormTextArea rules={[{required: true}]} label={'隐患内容'} name="source"/>
            <ProFormTextArea rules={[{required: true}]} label={'排查内容'} name="checkContent"/>
            <ProFormTextArea rules={[{required: true}]} label={'排查方式'} name="checkMode"/>
            <ProFormSelect
              rules={[{required: true}]}
              label={'隐患级别'}
              name="level"
              fieldProps={{
                optionLabelProp: 'children',
                optionItemRender(item) {
                  return <span style={{color: troubleColor[item.value]}}>{item.label}</span>;
                },
              }}
              valueEnum={troubleLevelData}
            />
            <ProFormSelect
              rules={[{required: true}]}
              label={'整改建议'}
              name="proposal"
              valueEnum={proposalData}
            />
            <ProFormTextArea rules={[{required: true}]} label={'整改措施'} name="measure"/>
            <ProFormSelect
              rules={[{required: true}]}
              label={'排查频次'}
              name="frequency"
              valueEnum={frequencyData}
              disabled={editMode && !checkMode}
            />
            <ProFormSelect
              name="handlerPost"
              label={'整改责任人岗位'}
              rules={[{required: true}]}
              request={requestPost}
              fieldProps={{
                placeholder: '请选择整改责任人岗位',
                dropdownMatchSelectWidth: false,
              }}
            />
            <ProFormDependency name={['handlerPost']}>
              {({handlerPost}) => {
                if (handlerPost)
                  return (
                    <ProFormSelect
                      name="handler"
                      label={'整改责任人'}
                      rules={[{required: true}]}
                      request={requestEmployee}
                      params={{postId: handlerPost}}
                      fieldProps={{
                        placeholder: '请选择责任岗位',
                        dropdownMatchSelectWidth: false,
                      }}
                    />
                  );
                return null;
              }}
            </ProFormDependency>
            <ProFormSelect
              name="verifierPost"
              label={'验收责任人岗位'}
              rules={[{required: true}]}
              request={requestPost}
              fieldProps={{
                placeholder: '请选择验收责任人岗位',
                dropdownMatchSelectWidth: false,
              }}
            />
            <ProFormDependency name={['verifierPost']}>
              {({verifierPost}) => {
                if (verifierPost)
                  return (
                    <ProFormSelect
                      name="verifier"
                      label={'验收责任人'}
                      rules={[{required: true}]}
                      request={requestEmployee}
                      params={{postId: verifierPost}}
                      fieldProps={{
                        placeholder: '请选择验收责任人岗位',
                        dropdownMatchSelectWidth: false,
                      }}
                    />
                  );

                return null;
              }}
            </ProFormDependency>
            <ProFormSelect
              rules={[{required: true}]}
              label={'状态'}
              name="status"
              valueEnum={{
                1: {
                  text: '启用',
                  status: 'Success',
                },
                2: {
                  text: '禁用',
                  status: 'Error',
                },
              }}
            />
          </ModalForm>

          <Drawer
            width={800}
            visible={showDetail}
            onClose={() => {
              setCurrentRow(undefined);
              setShowDetail(false);
            }}
            closable={false}
          >
            {currentRow?.place && (
              <ProDescriptions<TroubleListItem>
                column={1}
                bordered={true}
                title={currentRow?.place}
                request={getTrouble}
                layout={'horizontal'}
                params={currentRow}
                columns={columns as ProDescriptionsItemProps<TroubleListItem>[]}
              />
            )}
          </Drawer>
        </PageContainer>
      </Spin>
    </CheckModule>
  );
};

export default TroublePage;
